<?php

namespace common\modules\user\models\backend;

use common\widgets\grid\ActionColumn;
use Yii;
use yii\base\Model;
use yii\data\ArrayDataProvider;
use yii\debug\components\search\Filter;
use yii\debug\components\search\matchers;
use yii\debug\components\search\matchers\GreaterThan;
use yii\debug\components\search\matchers\LowerThan;
use yii\debug\components\search\matchers\SameAs;
use yii\helpers\ArrayHelper;

/**
 * Class RuleSearch
 *
 * @package common\modules\user\models\backend
 */
class RuleSearch extends Rule
{

    /**
     * @var string
     */
    public $className;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'className'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'className' => Yii::t('backend/user', 'Class Name'),
        ]);
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * @return string
     */
    public function classLabelName()
    {
        return Yii::t('backend/user', 'Rule List');
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ArrayDataProvider
     */
    public function search($params)
    {
        $models = Yii::$app->authManager->getRules();

        $dataProvider = new ArrayDataProvider([
            'allModels' => $models,
            'key'       => function ($model)
            {
                return ['name' => ArrayHelper::getValue($model, 'name')];
            },
            'sort'      => [
                'attributes' => ['name', 'ruleName', 'className', 'createdAt', 'updatedAt'],
            ],
        ]);

        if ( ! ($this->load($params) && $this->validate()))
        {
            return $dataProvider;
        }

        $filterData = ArrayHelper::toArray($models);
        foreach ($filterData as $k => $v)
        {
            if (isset($models[$k]))
            {
                /** @var \common\components\Rule $model */
                $model = $models[$k];
                $filterData[$k]['className'] = $model->className;
            }
        }

        $filter = new Filter();
        $this->addCondition($filter, 'name', true);
        $this->addCondition($filter, 'className', true);
        $dataProvider->allModels = $filter->filter($filterData);

        return $dataProvider;
    }

    /**
     * Adds filtering condition for a given attribute
     *
     * @param Filter  $filter    filter instance
     * @param string  $attribute attribute to filter
     * @param boolean $partial   if partial match should be used
     */
    public function addCondition(Filter $filter, $attribute, $partial = false)
    {
        $value = $this->$attribute;

        if (mb_strpos($value, '>') !== false)
        {
            $value = intval(str_replace('>', '', $value));
            $filter->addMatcher($attribute, new GreaterThan(['value' => $value]));

        }
        elseif (mb_strpos($value, '<') !== false)
        {
            $value = intval(str_replace('<', '', $value));
            $filter->addMatcher($attribute, new LowerThan(['value' => $value]));
        }
        else
        {
            $filter->addMatcher($attribute, new SameAs(['value' => $value, 'partial' => $partial]));
        }
    }

    /**
     * 返回字段的定义信息
     *
     * @return array
     */
    public function gridViewColumns()
    {
        return [
            'name',

            'className',

            [
                'attribute' => 'createdAt',
                'format'    => ['date', 'php:Y-m-d H:i:s'],
            ],

            [
                'attribute' => 'updatedAt',
                'format'    => ['date', 'php:Y-m-d H:i:s'],
            ],

            [
                'class' => ActionColumn::className(),
            ],
        ];
    }
}
